package com.example;

import brave.http.HttpTracing;
import brave.okhttp3.TracingInterceptor;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@SpringBootApplication
@RestController
@ComponentScan({"com.example","com.km"})
public class DemoApplication {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private HttpTracing httpTracing;

    @Bean
    public OkHttpClient okHttpClient() {
//        HttpTracing.Builder builder = HttpTracing.newBuilder(Tracing.current());
//        return new OkHttpClient.Builder()
//                .dispatcher(new Dispatcher(Tracing.current().currentTraceContext().executorService(new Dispatcher().executorService())))
//                .addNetworkInterceptor(TracingInterceptor.create(builder.build()))
//                .build();
        return new OkHttpClient.Builder()
                .dispatcher(new Dispatcher(httpTracing.tracing().currentTraceContext().executorService(new Dispatcher().executorService())))
                .addNetworkInterceptor(TracingInterceptor.create(httpTracing))
                .build();
    }

    @Autowired
    private OkHttpClient okHttpClient;

    @GetMapping("/step1")
    public String step1() {
        log.info("in /step1");
        Request request = new Request.Builder()
                .url("http://localhost:8090/step2")
                .build();
        Response response;
        try {
            response = okHttpClient.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "step1";
    }

    @GetMapping("/step2")
    public String step2() {
        log.info("in /step2");
        return "step2";
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
